package com.heima.article.controller.v1;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.service.IApArticleService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 文章内容
 */
@RestController
@RequestMapping("/api/v1/article/content")
public class ApArticleContentController {

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Resource
    private IApArticleService apArticleService;

    @Resource
    private ApArticleContentMapper apArticleContentMapper;

    /**
     * 测试文件上传
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/upload")
    public ResponseResult upload() throws Exception {

        // 1、获取文章内容
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                .last("limit 1"));
        String path = "";
        if (apArticleContent != null && StringUtils.isNotBlank(apArticleContent.getContent())) {
            // 2、文章内容通过freemarker生成html文件
            StringWriter out = new StringWriter();
            Template template = configuration.getTemplate("article.ftl");
            Map<String, Object> params = new HashMap<>();
            params.put("content", JSONArray.parseArray(apArticleContent.getContent()));
            template.process(params, out);
            ByteArrayInputStream is = new ByteArrayInputStream(out.toString().getBytes());

            // 3、把html文件上传到minio中
            path = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", is);

            // 4、把地址存储到数据库
            apArticleService.update(Wrappers.<ApArticle>lambdaUpdate()
                    .eq(ApArticle::getId, apArticleContent.getArticleId())
                    .set(ApArticle::getStaticUrl, path));
        }
        return ResponseResult.okResult(path);
    }

}
